<template>
	<view class="page-container">
		<!-- 筛选区 -->
		<u-picker :show="showProvince" :columns="provinceOptions" :defaultIndex=[3] keyName="admdivName"
			@cancel='showProvince=false' @confirm="handleProvinceChange"> </u-picker>
		<u-datetime-picker :show="showMonth" v-model="dateVal" mode="year-month" @cancel='showMonth=false' @confirm="handleMonthChange">
		</u-datetime-picker>
		<view class="filter-container">
			<!-- 开票省份筛选 -->
			<view class="province-select" @click="showProvince=true">
				<view>
					{{selectedProvince.admdivName}}
				</view>
				<u-icon name="arrow-down" size="16"></u-icon>
			</view>

			<!-- 开票月份筛选 -->
			<view class="province-select" @click="showMonth=true">
				<view>
					{{selectedMonth}}
				</view>
				<u-icon name="arrow-down" size="16"></u-icon>
			</view>
			<u-button type="primary" text="查询" @click="onSearch"></u-button>
		</view>

		<!-- 票据列表区域 -->
		<view class="bill-list-container">
			<view class="bill-list-header">
				<text class="bill-count">找到 {{ billList.length }} 张匹配票据</text>
				<text class="select-tip">点击卡片选中</text>
			</view>
			<!-- 票据列表 -->
			<view class="bill-list">
				<u-list :height="listHeight" @scrolltolower="scrolltolower">
					<view v-for="(bill, index) in billList" :key="index" class="bill-item"
						:class="{ 'bill-selected': bill.selected }" @click="toggleBillSelect(index)">
						<view class="bill-header">
							<text class="bill-title">{{ bill.invoicingPartyName }}</text>
							<view class="status-label"
								:class="bill.accountState==0?'status-invalid':(bill.accountState==1?'status-progress':(bill.accountState==2?'status-normal':('')))">
								<text
									class="status-text">{{ bill.accountState==0?'未报销':(bill.accountState==1?'报销中':(bill.accountState==2?'已报销':(''))) }}</text>
							</view>
						</view>

						<view class="bill-info">
							<view class="info-row">
								<text class="info-label">票据种类</text>
								<text class="info-value">{{ bill.eInvoiceName }}</text>
							</view>
							<view class="info-row">
								<text class="info-label">票据代码</text>
								<text class="info-value">{{ bill.eInvoiceCode }}</text>
							</view>
							<view class="info-row">
								<text class="info-label">票据号码</text>
								<text class="info-value">{{ bill.eInvoiceNumber }}</text>
							</view>
							<view class="info-row total-row">
								<text class="info-label">金额</text>
								<text class="info-value amount">￥ {{ (bill.totalAmount).toFixed(2) }}</text>
							</view>
						</view>
					</view>
				<u-loadmore v-if="billList.length>0" :status="dataTip" loadmore-text="上滑加载更多" />
				</u-list>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<u-button class="confirm-btn" type="primary" :disabled="selectedCount === 0" @click="confirmSelect">
				确认选择（{{ selectedCount }}张）
			</u-button>
		</view>

	</view>
</template>

<script>
	import {
		showProvince
	} from '@/api/api.js'
	import {
		crossProQueryEInvoice
	} from '@/api/homeApi.js'
	export default {
		data() {
      return {
        listHeight: uni.getSystemInfoSync().windowHeight - 270,
				dateVal:Number(new Date()),
				dataTip: 'loadmore', //加载前值为loadmore，加载中为loading，没有数据为nomore
				showProvince: false,
				selectedProvince: {
					admdivName: '河北省',
					admdivCode: '130000'
				},
				showMonth: false,
				selectedMonth:'请选择日期',
				// 筛选选项
				provinceOptions: [],
				// 票据数据
				billList: [],
				selectedCount: 0,
				currentPage: 1,
				pageSize: 5
			};
		},
		created() {
			this.conversionDate()
			this.showProvinceFun()
			this.onSearch()
		},
		computed:{
			// conversionDate(){
			// 	const date = new Date();
			// 	// 格式化为 "YYYY年MM月"
			// 	const year = date.getFullYear();
			// 	const month = date.getMonth() + 1;
			// 	const nowDate = `${year}-${month < 10 ? '0' + month : month}`;
			// 	console.log('===',nowDate)
			// 	return nowDate
			// },
		},
		methods: {
			conversionDate(){
				const date = new Date();
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const nowDate = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('===',nowDate)
				this.selectedMonth=nowDate
			},
			async onSearch() {
				if (this.selectedMonth == '请选择日期') {
					return this.$u.toast('请选择日期');
				}
				uni.showLoading({
					title: '查询中'
				})
				this.currentPage = 1
				this.billList = []
				const [year, month] = this.selectedMonth.split('-')
				const startDate = year + month + '01'
				const lastDate = year + month + this.getLastDay(this.selectedMonth)
				const params = {
					supervisorAreaCode: this.selectedProvince.admdivCode.substring(0, 2),
					bgnDate: startDate,
					endDate: lastDate,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				}
				const res = await crossProQueryEInvoice(params)
				if (res.result == 0) {
					if (res.singleData.eInvoiceList.length < this.pageSize) {
						this.dataTip = 'nomore'
					}
					this.billList = res.singleData.eInvoiceList
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},

			scrolltolower() {
				if (this.dataTip == 'nomore' || this.dataTip == 'loading') {
					return
				}
				this.currentPage += 1
				console.log('daodile', this.currentPage)
				this.loadmore();
			},
			async loadmore() {
				const [year, month] = this.selectedMonth.split('-')
				const startDate = year + month + '01'
				const lastDate = year + month + this.getLastDay(this.selectedMonth)
				this.dataTip = 'loading'
				const res = await crossProQueryEInvoice({
					supervisorAreaCode: this.selectedProvince.admdivCode.substring(0, 2),
					bgnDate: startDate,
					endDate: lastDate,
					currentPage: this.currentPage,
					pageSize: this.pageSize,
				})
				if (res.result == 0) {
					console.log('res', res)
					this.billList = this.billList.concat(res.singleData.eInvoiceList)
					if (res.singleData.eInvoiceList.length < this.pageSize) {
						this.dataTip = 'nomore'
					} else {
						this.dataTip = 'loadmore'
					}
				} else {
					this.$u.toast(res.message || '接口错误');
				}
			},
			async showProvinceFun() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await showProvince()
				if (res.result == 0) {
					this.provinceOptions[0] = res.data
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},
			// 省份变化处理
			handleProvinceChange(e) {
				this.showProvince = false
				console.log('===', e)
				this.selectedProvince = e.value[0]
				// 实际项目中可根据省份加载单位列表
			},
			handleMonthChange(e) {
				this.showMonth = false;
				// e.value 是时间戳
				const date = new Date(e.value);
				// 格式化为 "YYYY年MM月"
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				this.selectedMonth = `${year}-${month < 10 ? '0' + month : month}`;
				console.log('选择的月份:', this.selectedMonth);
			},

			// 切换票据选中状态
			toggleBillSelect(index) {
				if (this.billList[index].accountState == 1) {
					this.$u.toast('不可选择报销中票据！');
				} else {
					this.billList[index].selected = !this.billList[index].selected;
					this.updateSelectedCount();
				}
			},

			// 更新选中数量
			updateSelectedCount() {
				this.selectedCount = this.billList.filter(bill => bill.selected).length;
			},

			// 确认选择
			confirmSelect() {
				const selectedBills = this.billList.filter(bill => bill.selected);
				// 这里可以处理选中的票据数据，例如返回上一页并携带数据
				uni.navigateBack({
					delta: 1,
					success: () => {
						uni.$emit('selectedBills', selectedBills)
					}
				})
			},
			getLastDay(date) {
				// 输入的年月字符串
				const yearMonth = date;
				// 分割成年和月（注意月份在 JS 中是 0 开始的，需要减 1）
				const [year, month] = yearMonth.split('-').map(Number);
				// 构造下一个月的第一天（例如 2025-02 的下一个月第一天是 2025-03-01）
				const nextMonthFirstDay = new Date(year, month, 1);
				// 减去 1 天，得到当前月的最后一天
				const lastDay = new Date(nextMonthFirstDay - 24 * 60 * 60 * 1000);
				// 格式化结果（获取日期部分）
				const lastDate = lastDay.getDate(); // 例如 2025-02 的最后一天是 28，结果为 28
				return lastDate
			},
		}
	};
</script>

<style lang="scss" scoped>
	/* 基础样式 */
	.page-container {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		font-size: 28rpx;
		color: #272E3B;
	}

	/* 导航栏样式 */
	.navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #ffffff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 99;
	}

	.navbar-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		height: 100%;
	}

	.navbar-left {
		display: flex;
		align-items: center;
	}

	.navbar-back-text {
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #272E3B;
	}

	.navbar-title {
		font-size: 32rpx;
		font-weight: 600;
	}

	.navbar-right {
		width: 80rpx;
	}

	/* 筛选区样式 */
	.filter-container {
		padding: 24rpx 30rpx;
		background-color: #ffffff;
		display: grid;
		gap: 15rpx;
	}

	.province-select {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		height: 60rpx;
		padding: 10rpx;
		/* 120px -> 180rpx */
	}

	.filter-grid {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 20rpx;
	}

	.select-component {
		width: 100%;
		height: 72rpx;
		border-radius: 16rpx;
		border: 2rpx solid #e5e5e5;
	}

	/* 票据列表区域 */
	.bill-list-container {
		padding: 30rpx;
		padding-bottom: 160rpx;
	}

	.bill-list-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 24rpx;
	}

	.bill-count {
		font-size: 28rpx;
		font-weight: 500;
	}

	.select-tip {
		font-size: 26rpx;
		color: #86909C;
	}

	/* 加载状态 */
	.loading-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 160rpx 0;
	}

	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #86909C;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 160rpx 0;
	}

	.empty-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #86909C;
	}

	.empty-subtext {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #86909C;
	}

	/* 票据列表 */
	.bill-list {
		display: flex;
		flex-direction: column;
		// gap: 24rpx;
	}

	.bill-item {
		margin: 12rpx 0;
		background-color: #F7F8FA;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
		transition: all 0.3s;
	}

	.bill-item:hover {
		box-shadow: 0 8rpx 24rpx rgba(22, 93, 255, 0.15);
	}

	.bill-selected {
		border: 4rpx solid #165DFF;
		box-shadow: 0 8rpx 24rpx rgba(22, 93, 255, 0.15);
	}

	.bill-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 24rpx;
	}

	.bill-title {
		font-size: 30rpx;
		font-weight: 600;
	}

	.status-label {
		padding: 6rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.status-invalid {
		background-color: rgba(245, 63, 63, 0.1);
		color: #F53F3F;
	}

	.status-normal {
		background-color: rgba(134, 144, 156, 0.1);
		color: #86909C;
	}

	.status-progress {
		background-color: rgba(0, 180, 42, 0.1);
		color: #00B42A;
	}

	.bill-info {
		display: flex;
		flex-direction: column;
	}

	.info-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		font-size: 26rpx;
	}

	.info-row:last-child {
		margin-bottom: 0;
	}

	.info-label {
		color: #86909C;
	}

	.total-row {
		padding-top: 20rpx;
		margin-top: 10rpx;
		border-top: 2rpx solid #f0f0f0;
	}

	.amount {
		color: #165DFF;
		font-weight: 600;
	}

	/* 底部操作栏 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 24rpx 30rpx;
		background-color: #ffffff;
		box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.05);
	}
</style>